package com.snoweagler.verify;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class ImageCodeVerifyFilter extends OncePerRequestFilter {
    @Resource
    private AuthenticationFailureHandler authenticationFailureHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (StringUtils.equals("/login", request.getRequestURI()) && StringUtils.equalsIgnoreCase(request.getMethod(), "post")){
            try {
                verify(response,request);
            }catch (AuthenticationException e){
                authenticationFailureHandler.onAuthenticationFailure(request,response, e);
                return;
            }
        }
        filterChain.doFilter(request,response);
    }

    private void verify(HttpServletResponse response, HttpServletRequest request) throws ServletRequestBindingException {
        String imageCode = ServletRequestUtils.getStringParameter(request, "imageCode");

        if(StringUtils.isBlank(imageCode)){
            throw new ImageException("请输入验证码");
        }
        ImageCode imageCodeInSession = (ImageCode)request.getSession().getAttribute("imageCode");
    }
}
